import Vue from 'vue'
import VueRouter from 'vue-router'

import Login from '../components/Login/Login'
import Home from '../components/Home/Home'
import Welcome from '../components/Welcome/Welcome'
import User from '../components/Users/User'
import Rights from '../components/Right/Rights'
import Role from '../components/Role/Role'
import Category from '../components/Goods/Category'
import Params from '../components/Param/Param'

Vue.use(VueRouter)

const routes = [
  {
    path: "/",
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    redirect: "/welcome",
    children: [
      {
        path: '/welcome',
        name: 'Welcome',
        component: Welcome
      },
      {
        path: '/users',
        name: 'User',
        component: User
      },
      {
        path: '/rights',
        name: 'Rights',
        component: Rights
      },
      {
        path: '/roles',
        name: 'Role',
        component: Role
      },
      {
        path: '/categories',
        name: 'Category',
        component: Category,
      },
      {
        path: '/params',
        name: 'Params',
        component: Params,
      },
    ]
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 挂载一个导航守卫
router.beforeEach( (to,from,next) => {
  // 放行 login
  if (to.path === '/login') return next();
  // 取token值
  const token = window.sessionStorage.getItem("token");
  // 如果token为null 强行跳转到登录
  if (!token) return next('/login');
  // token不为空 放行
  return next()
  
})

export default router
